using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ICP_MS.Plugin.HPLC;

public class ExperimentDatas
{
	public const int AcqInterval = 2;

	private List<AnalyteIsotope> selectIsotopes = new List<AnalyteIsotope>();

	private IList<ScanRegions> surveyRegions = new List<ScanRegions>();

	private IList<ScanRegions> scanRegions = new List<ScanRegions>();

	private List<PeakRegions> peakRegions = new List<PeakRegions>();

	private List<IsotopeInfos> isotopes = new List<IsotopeInfos>();

	private List<IsotopeRatio> ratios = new List<IsotopeRatio>();

	private List<SamplesInfos> samples = new List<SamplesInfos>();

	private List<STDConcentration> stdConcentration = new List<STDConcentration>();

	private List<HPLCAnalyseInfos> results = new List<HPLCAnalyseInfos>();

	private List<HPLCStatisticResults> statistics = new List<HPLCStatisticResults>();

	private List<RatioResults> ratioResults = new List<RatioResults>();

	private List<RatioStatistics> ratioStat = new List<RatioStatistics>();

	private List<SpectrumInfos> spectrums = new List<SpectrumInfos>();

	private List<HPLCIsotopeCurve> curves = new List<HPLCIsotopeCurve>();

	private ReportParams reportParams = new ReportParams
	{
		ShowRuns = true,
		ShowMean = true,
		ShowSd = true,
		ShowRsd = true,
		ShowConc = true,
		ShowCPS = true,
		ShowUCPS = true,
		ShowCurve = true,
		Header = "钢研纳克检测技术有限公司",
		Title = "MS-300 测试结果",
		Logo = null
	};

	private ScanParams scanParams = new ScanParams();

	private IList<PointF> disallowedRanges = new List<PointF>();

	private List<HPLCIntegerRegions> integerRegions = new List<HPLCIntegerRegions>();

	private List<HPLCTimeSpectrum> timeSpectrums = new List<HPLCTimeSpectrum>();

	private List<AcqTime> acqTimes = new List<AcqTime>();

	private AutoResetEvent scanEvent = new AutoResetEvent(initialState: false);

	private string internalSchema = "Default";

	private bool isInCalculate = false;

	private DirtyInfo dirty = new DirtyInfo();

	private double[][] surveyMass = null;

	private double[] scanMass = null;

	private double[] peakMass = null;

	private int[] resolutions = null;

	public AutoSampleTable AutosampleTable { get; set; }

	public Platform CurrentPlat { get; set; }

	public X2Lens CurrentLens { get; set; }

	public PlasmaPara CurrentPlasma { get; set; }

	public RFS CurrentRFS { get; set; }

	public Injector CurrentInjector { get; set; }

	public StableConfig StableConfig { get; set; }

	public List<AnalyteIsotope> SelectIsotopes
	{
		get
		{
			return selectIsotopes;
		}
		set
		{
			selectIsotopes = value;
		}
	}

	public IList<ScanRegions> SurveyRegions
	{
		get
		{
			return surveyRegions;
		}
		set
		{
			surveyRegions = value;
		}
	}

	public IList<ScanRegions> ScanRegions
	{
		get
		{
			return scanRegions;
		}
		set
		{
			scanRegions = value;
		}
	}

	public List<PeakRegions> PeakRegions
	{
		get
		{
			return peakRegions;
		}
		set
		{
			peakRegions = value;
		}
	}

	public List<IsotopeInfos> Isotopes
	{
		get
		{
			return isotopes;
		}
		set
		{
			isotopes = value;
		}
	}

	public List<IsotopeRatio> Ratios
	{
		get
		{
			return ratios;
		}
		set
		{
			ratios = value;
		}
	}

	public List<SamplesInfos> Samples
	{
		get
		{
			return samples;
		}
		set
		{
			samples = value;
		}
	}

	public List<STDConcentration> StdConcentration
	{
		get
		{
			return stdConcentration;
		}
		set
		{
			stdConcentration = value;
		}
	}

	public List<HPLCAnalyseInfos> Results
	{
		get
		{
			return results;
		}
		set
		{
			results = value;
		}
	}

	public List<HPLCStatisticResults> Statistics
	{
		get
		{
			return statistics;
		}
		set
		{
			statistics = value;
		}
	}

	public List<RatioResults> RatioResults
	{
		get
		{
			return ratioResults;
		}
		set
		{
			ratioResults = value;
		}
	}

	public List<RatioStatistics> RatioStat
	{
		get
		{
			return ratioStat;
		}
		set
		{
			ratioStat = value;
		}
	}

	public List<SpectrumInfos> Spectrums
	{
		get
		{
			return spectrums;
		}
		set
		{
			spectrums = value;
		}
	}

	public List<HPLCIsotopeCurve> Curves
	{
		get
		{
			return curves;
		}
		set
		{
			curves = value;
		}
	}

	public ReportParams ReportParams
	{
		get
		{
			return reportParams;
		}
		set
		{
			reportParams = value;
		}
	}

	public ScanParams Scan
	{
		get
		{
			return scanParams;
		}
		set
		{
			scanParams = value;
		}
	}

	public IList<PointF> DisallowedRanges => disallowedRanges;

	public List<HPLCIntegerRegions> IntegerRegions => integerRegions;

	public List<HPLCTimeSpectrum> TimeSpectrums => timeSpectrums;

	public List<AcqTime> AcqTimes => acqTimes;

	public string InternalSchema
	{
		get
		{
			return internalSchema;
		}
		set
		{
			internalSchema = value;
		}
	}

	public DirtyInfo Dirty => dirty;

	public bool IsRun { get; set; }

	public event EventHandler<ExperimentEventArgs> EventExperiment = null;

	public event EventHandler applyEnable = null;

	public event EventHandler<CurveInfoEventArgs> SingleAcq = null;

	public event EventHandler isotopeChanged = null;

	public event EventHandler istdChanged = null;

	public event EventHandler sampleChanged = null;

	public event EventHandler methodChanged = null;

	public event EventHandler regionChanged = null;

	public event EventHandler IsAutoSamplerChangedEvent = null;

	public void SortIsotopes()
	{
		Isotopes.Sort((IsotopeInfos isotope1, IsotopeInfos isotope2) => isotope1.mass.CompareTo(isotope2.mass));
	}

	public void SetupIsotopeInfos()
	{
		Isotopes.RemoveAll((IsotopeInfos isotope) => !SelectIsotopes.Exists((AnalyteIsotope selectIsotope) => selectIsotope.symbol == isotope.symbol));
		SelectIsotopes.ForEach(delegate(AnalyteIsotope selectIsotope)
		{
			if (!Isotopes.Exists((IsotopeInfos isotope) => isotope.symbol == selectIsotope.symbol))
			{
				Isotopes.Add(new IsotopeInfos
				{
					id = selectIsotope.id,
					symbol = selectIsotope.symbol,
					mass = selectIsotope.mass,
					name = "Default",
					units = "ppb",
					visible = true,
					technique = Lang.Txt("FormStandard.Istd.Technique.None.Text"),
					force = 0,
					withInterference = selectIsotope.withInterference,
					isInterference = false
				});
			}
			else
			{
				IsotopeInfos isotopeInfos = Isotopes.Find((IsotopeInfos isotope) => isotope.symbol == selectIsotope.symbol);
				isotopeInfos.isInterference = false;
			}
		});
		Dirty.IsotopeInfoDirty = true;
	}

	public void SetupResultsByAddIntegerRegions(HPLCIntegerRegions region)
	{
		Results.RemoveAll((HPLCAnalyseInfos r) => r.regionLabel == region.ReferenceId);
		Statistics.RemoveAll((HPLCStatisticResults r) => r.regionLabel == region.ReferenceId);
		Curves.RemoveAll((HPLCIsotopeCurve r) => r.regionLabel == region.ReferenceId);
		foreach (IsotopeInfos isotope in Isotopes)
		{
			foreach (SamplesInfos sample2 in Samples)
			{
				for (int num = 0; num < sample2.mains; num++)
				{
					Results.Add(new HPLCAnalyseInfos
					{
						isotopeId = isotope.id,
						symbol = isotope.symbol,
						regionLabel = region.ReferenceId,
						sampleId = sample2.guid,
						label = sample2.label,
						number = num,
						test = false,
						intensity = -1.0
					});
				}
			}
			foreach (SamplesInfos sample in Samples)
			{
				Statistics.Add(new HPLCStatisticResults
				{
					isotopeId = isotope.id,
					symbol = isotope.symbol,
					sampleId = sample.guid,
					regionLabel = region.ReferenceId,
					label = sample.label,
					avgCon = -1.0,
					avgUICPS = -1.0,
					avgCPS = -1.0,
					sdCon = -1.0,
					sdUICPS = -1.0,
					sdCPS = -1.0,
					rsdCon = -1.0,
					rsdUICPS = -1.0,
					rsdCPS = -1.0,
					include = true
				});
			}
			Curves.Add(new HPLCIsotopeCurve
			{
				isotopeId = isotope.id,
				symbol = isotope.symbol,
				regionLabel = region.ReferenceId,
				k = 1.0,
				b = 0.0,
				r = 1.0,
				intercept1 = 0.0,
				intercept2 = 0.0,
				calculated = false
			});
		}
	}

	public void SetupResultsByDeleteIntegerRegions(HPLCIntegerRegions region)
	{
		Results.RemoveAll((HPLCAnalyseInfos r) => r.regionLabel == region.ReferenceId);
		Statistics.RemoveAll((HPLCStatisticResults r) => r.regionLabel == region.ReferenceId);
		Curves.RemoveAll((HPLCIsotopeCurve r) => r.regionLabel == region.ReferenceId);
	}

	public void UpdateResultsBySampleId(SamplesInfos sample)
	{
		Results.RemoveAll((HPLCAnalyseInfos r) => r.sampleId == sample.guid);
		Statistics.RemoveAll((HPLCStatisticResults r) => r.sampleId == sample.guid);
		foreach (IsotopeInfos isotope in Isotopes)
		{
			foreach (HPLCIntegerRegions region in integerRegions)
			{
				for (int num = 0; num < sample.mains; num++)
				{
					Results.Add(new HPLCAnalyseInfos
					{
						isotopeId = isotope.id,
						symbol = isotope.symbol,
						sampleId = sample.guid,
						regionLabel = region.ReferenceId,
						label = sample.label,
						number = num,
						test = false,
						intensity = -1.0,
						concentration = -1.0,
						icps = -1.0
					});
				}
				Statistics.Add(new HPLCStatisticResults
				{
					isotopeId = isotope.id,
					symbol = isotope.symbol,
					sampleId = sample.guid,
					regionLabel = region.ReferenceId,
					label = sample.label,
					avgCon = -1.0,
					avgUICPS = -1.0,
					avgCPS = -1.0,
					sdCon = -1.0,
					sdUICPS = -1.0,
					sdCPS = -1.0,
					rsdCon = -1.0,
					rsdUICPS = -1.0,
					rsdCPS = -1.0,
					include = true
				});
			}
		}
	}

	public void FillStdConcentration()
	{
		StdConcentration.RemoveAll((STDConcentration std) => !Samples.Exists((SamplesInfos sample) => sample.guid == std.sample) || !Isotopes.Exists((IsotopeInfos isotope) => isotope.symbol == std.symbol) || !IntegerRegions.Exists((HPLCIntegerRegions interregion) => interregion.ReferenceId == std.Regionlabel));
		StdConcentration.RemoveAll((STDConcentration std) => Samples.Exists((SamplesInfos sample) => sample.guid == std.sample && (sample.type == 0 || sample.type == 3)));
		foreach (SamplesInfos sample2 in Samples)
		{
			if (sample2.type != 1 && sample2.type != 2)
			{
				continue;
			}
			foreach (IsotopeInfos isotope2 in Isotopes)
			{
				IEnumerable<HPLCIntegerRegions> regions = integerRegions.Where((HPLCIntegerRegions rgs) => rgs.symbol == isotope2.symbol);
				foreach (HPLCIntegerRegions region in regions)
				{
					if (!StdConcentration.Exists((STDConcentration std) => std.sample == sample2.guid && std.symbol == isotope2.symbol && std.Regionlabel == region.ReferenceId))
					{
						STDConcentration standard = new STDConcentration
						{
							label = sample2.label,
							symbol = isotope2.symbol,
							Regionlabel = region.ReferenceId,
							inter = isotope2.inter,
							sample = sample2.guid,
							concentration = -1.0,
							method = isotope2.method
						};
						StdConcentration.Add(standard);
					}
				}
			}
		}
	}

	public void SetupRatioResults()
	{
		IEnumerable<string> names = Ratios.Select((IsotopeRatio isotope) => isotope.Name);
		ratioResults.RemoveAll((RatioResults r) => !names.Contains(r.Name));
		RatioStat.RemoveAll((RatioStatistics r) => !names.Contains(r.Name));
		IEnumerable<string> r_names = ratioResults.Select((RatioResults result) => result.Name);
		foreach (IsotopeRatio isotope2 in Ratios)
		{
			if (r_names.Contains(isotope2.Name))
			{
				continue;
			}
			foreach (SamplesInfos sample in Samples)
			{
				ratioStat.Add(new RatioStatistics
				{
					Name = isotope2.Name,
					Numerator = isotope2.NumeratorSym,
					Denominator = isotope2.DenominatorSym,
					SampleId = sample.guid,
					Label = sample.label,
					Sd = -1.0,
					Rsd = -1.0,
					Avg = -1.0
				});
				for (int num = 0; num < sample.mains; num++)
				{
					ratioResults.Add(new RatioResults
					{
						Name = isotope2.Name,
						Numerator = isotope2.NumeratorSym,
						Denominator = isotope2.DenominatorSym,
						SampleId = sample.guid,
						Label = sample.label,
						Number = num,
						Result = -1.0
					});
				}
			}
		}
	}

	private bool InitRunMass()
	{
		List<double> tmp = new List<double>();
		List<int> resolution = new List<int>();
		foreach (PeakRegions region in PeakRegions)
		{
			for (int i = -region.channels / 2; i <= region.channels / 2; i++)
			{
				tmp.Add(region.mass + (double)i * region.separation);
				resolution.Add((region.resolution == Lang.Txt("FormScanLA.Standard")) ? 1 : ((!(region.resolution == Lang.Txt("ADDTune.TuneDebug.High"))) ? 2 : 0));
			}
			RFManager.rfs.dwell = region.dwell;
		}
		Detector.Instance.msDetectorRF.SetDwell();
		peakMass = tmp.ToArray();
		resolutions = resolution.ToArray();
		return true;
	}

	private void InitCurve()
	{
		foreach (IsotopeInfos isotope in Isotopes)
		{
			IEnumerable<HPLCIntegerRegions> regions = integerRegions.Where((HPLCIntegerRegions Regions) => Regions.symbol == isotope.symbol);
			foreach (HPLCIntegerRegions region in regions)
			{
				if (!Curves.Exists((HPLCIsotopeCurve curve) => region.ReferenceId == curve.regionLabel))
				{
					Curves.Add(new HPLCIsotopeCurve
					{
						isotopeId = isotope.id,
						symbol = isotope.symbol,
						regionLabel = region.ReferenceId,
						k = 1.0,
						b = 0.0,
						r = 1.0,
						intercept1 = 0.0,
						intercept2 = 0.0,
						calculated = false
					});
				}
			}
		}
	}

	private void InitResult(SamplesInfos sample)
	{
		Results.RemoveAll((HPLCAnalyseInfos result) => result.sampleId == sample.guid);
		Statistics.RemoveAll((HPLCStatisticResults result) => result.sampleId == sample.guid);
		foreach (IsotopeInfos isotope in Isotopes)
		{
			IEnumerable<HPLCIntegerRegions> regions = integerRegions.Where((HPLCIntegerRegions Regions) => Regions.symbol == isotope.symbol && Regions.sampleId == sample.guid);
			foreach (HPLCIntegerRegions region in regions)
			{
				for (int num2 = 0; num2 < sample.mains; num2++)
				{
					Results.Add(new HPLCAnalyseInfos
					{
						isotopeId = isotope.id,
						symbol = isotope.symbol,
						regionLabel = region.ReferenceId,
						sampleId = sample.guid,
						label = sample.label,
						number = num2,
						test = false,
						intensity = -1.0,
						concentration = -1.0,
						icps = -1.0
					});
				}
				Statistics.Add(new HPLCStatisticResults
				{
					isotopeId = isotope.id,
					symbol = isotope.symbol,
					sampleId = sample.guid,
					regionLabel = region.ReferenceId,
					label = sample.label,
					avgCon = -1.0,
					avgUICPS = -1.0,
					avgCPS = -1.0,
					sdCon = -1.0,
					sdUICPS = -1.0,
					sdCPS = -1.0,
					rsdCon = -1.0,
					rsdUICPS = -1.0,
					rsdCPS = -1.0,
					include = true
				});
			}
		}
		RatioResults.RemoveAll((RatioResults ratio) => ratio.SampleId == sample.guid);
		RatioStat.RemoveAll((RatioStatistics ratio) => ratio.SampleId == sample.guid);
		foreach (IsotopeRatio isotope2 in Ratios)
		{
			ratioStat.Add(new RatioStatistics
			{
				Name = isotope2.Name,
				Numerator = isotope2.NumeratorSym,
				Denominator = isotope2.DenominatorSym,
				SampleId = sample.guid,
				Label = sample.label,
				Sd = -1.0,
				Rsd = -1.0,
				Avg = -1.0
			});
			for (int num = 0; num < sample.mains; num++)
			{
				ratioResults.Add(new RatioResults
				{
					Name = isotope2.Name,
					Numerator = isotope2.NumeratorSym,
					Denominator = isotope2.DenominatorSym,
					SampleId = sample.guid,
					Label = sample.label,
					Number = num,
					Result = -1.0
				});
			}
		}
	}

	private void InitSpectrum(SamplesInfos sample)
	{
		timeSpectrums.RemoveAll((HPLCTimeSpectrum spectrum) => spectrum.SampleId == sample.guid);
		foreach (IsotopeInfos isotope in isotopes)
		{
			for (int i = 0; i < sample.mains; i++)
			{
				timeSpectrums.Add(new HPLCTimeSpectrum
				{
					SampleId = sample.guid,
					SampleLabel = sample.label,
					IsotopeId = isotope.id,
					Symbol = isotope.symbol,
					RunIndex = i
				});
			}
		}
	}

	public bool PreRun()
	{
		if (!InitRunMass())
		{
			MessageBox.Show("请检查是否选择了分析元素，或者选中了扫描模式", "提示", MessageBoxButtons.OK);
			return false;
		}
		return true;
	}

	public void StartRun()
	{
		IsRun = true;
		Detector.Instance.ExperimentState = 5;
		InitCurve();
		Detector.finishReceive += Detector_massFinishReceive;
		Scan.currentStatus = 1;
		if (this.applyEnable != null)
		{
			this.applyEnable(this, null);
		}
		Task.Factory.StartNew(RunExperiment);
	}

	private void Detector_errorReceive(object sender, ErrorMsgEventArgs e)
	{
		LensManager.x2lens.Etp = 0.0;
		LensManager.Instance.SetEtp();
		StopRun();
		MessageBox.Show("质量数为" + e.X + "元素浓度过高请检查，已停止测试！", "警告-倍增器保护");
	}

	public void StopRun(bool stopApply = true)
	{
		if (IsRun)
		{
			scanEvent.Set();
			IsRun = false;
			Detector.finishReceive -= Detector_massFinishReceive;
			Detector.Instance.Stop();
			if (stopApply)
			{
				Scan.currentStatus = 2;
			}
			else
			{
				Scan.currentStatus = 3;
			}
			Detector.Instance.ExperimentState = -1;
			this.EventExperiment(null, new ExperimentEventArgs(null, 3, 0, 0));
		}
	}

	public void RunExperiment()
	{
		bool acqError = false;
		scanEvent.Reset();
		while (IsRun)
		{
			IEnumerable<SamplesInfos> ss = Samples.Where((SamplesInfos s) => s.status != 1);
			if (ss.Count() > 0)
			{
				if (!IsRun)
				{
					break;
				}
				SamplesInfos currentSample = ss.First();
				ExperimentPrepare(currentSample);
				MyTimers.timeBeginPeriod(1);
				acqError = !ExperimentMainRun(currentSample);
				if (acqError)
				{
					break;
				}
				MyTimers.timeEndPeriod(1);
				currentSample.status = 1;
			}
			else
			{
				StopRun(stopApply: false);
			}
		}
		StopRun();
		if (this.EventExperiment != null)
		{
			this.EventExperiment(null, new ExperimentEventArgs(null, acqError ? (-1) : 3, 0, 0));
		}
	}

	private bool ExperimentPrepare(SamplesInfos currentSample)
	{
		if (this.EventExperiment != null)
		{
			this.EventExperiment(null, new ExperimentEventArgs(currentSample, 0, 0, 0));
		}
		currentSample.time = DateTime.Now;
		currentSample.status = -1;
		InitResult(currentSample);
		InitSpectrum(currentSample);
		return true;
	}

	private bool ExperimentMainRun(SamplesInfos currentSample)
	{
		IEnumerable<AcqTime> acqInfos = acqTimes.Where((AcqTime acq) => acq.SampleId == currentSample.guid);
		int acqTime = 60;
		int acqSweep = 20;
		if (acqInfos.Any())
		{
			acqTime = acqInfos.First().Time;
			acqSweep = acqInfos.First().Sweeps;
		}
		for (int runIndex = 0; runIndex < currentSample.mains; runIndex++)
		{
			Detector.msDetectorPara.InitIntensity();
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 4, runIndex, 0));
			}
			if (!IsRun)
			{
				return false;
			}
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 1, runIndex, 0));
			}
			if (this.EventExperiment != null)
			{
				this.EventExperiment(null, new ExperimentEventArgs(currentSample, 5, runIndex, 0));
			}
			double time = 0.0;
			uint tstart = MyTimers.timeGetTime();
			while (time < (double)acqTime)
			{
				if (!IsRun)
				{
					return true;
				}
				time = (double)(MyTimers.timeGetTime() - tstart) / 1000.0;
				if (this.EventExperiment != null)
				{
					this.EventExperiment(null, new ExperimentEventArgs(currentSample, 2, runIndex, (int)time));
				}
				for (int sweepIndex = 0; sweepIndex < acqSweep; sweepIndex++)
				{
					if (!IsRun)
					{
						return true;
					}
					if (sweepIndex == 0)
					{
						Detector.Instance.SetMassAxis(peakMass.ToArray());
					}
					Detector.Instance.SendHopDatas(peakMass.ToArray(), resolutions.ToArray(), true, false);
					if (!scanEvent.WaitOne(10000))
					{
						Log.InsertLog("数据采集", "数据采集错误", Lang.Txt("FormExperLog.Text3"), (Severity)3);
						return false;
					}
				}
				SpectrumInfos currentSpectrum = new SpectrumInfos
				{
					sampleId = currentSample.guid
				};
				ProcessSpectums(currentSpectrum, acqSweep);
				ProcessMainRunDatas(currentSpectrum, runIndex, time);
				if (this.SingleAcq != null)
				{
					this.SingleAcq.BeginInvoke(null, new CurveInfoEventArgs(currentSample.guid, runIndex), null, null);
				}
			}
		}
		currentSample.status = 1;
		return true;
	}

	private void Detector_massFinishReceive(object sender, EventArgs e)
	{
		scanEvent.Set();
	}

	private void ProcessSpectums(SpectrumInfos spectrum, int sweeps)
	{
		int nlenth = Detector.msDetectorPara.Mass.Length;
		spectrum.mass = new double[nlenth];
		spectrum.intensityAnalog = new double[nlenth];
		spectrum.intensityPulse = new double[nlenth];
		spectrum.intensity = new double[nlenth];
		Array.Copy(Detector.msDetectorPara.Mass, spectrum.mass, nlenth);
		for (int i = 0; i < nlenth; i++)
		{
			double pafactor = Detector.Instance.dacPAFactors[(int)(spectrum.mass[i] * 100.0)];
			spectrum.intensityAnalog[i] = Detector.msDetectorPara.IntesnsityAnalog[i] / (double)sweeps;
			spectrum.intensityPulse[i] = Detector.msDetectorPara.IntesnsityPulse[i] / (double)sweeps;
			if (Detector.detectorConfig.IsNewBoard)
			{
				spectrum.intensity[i] = ((spectrum.intensityAnalog[i] > Detector.detectorConfig.PaThreshold) ? (spectrum.intensityAnalog[i] * pafactor + Detector.detectorConfig.DetectorB) : spectrum.intensityPulse[i]);
			}
			else
			{
				spectrum.intensity[i] = ((spectrum.intensityPulse[i] < Detector.detectorConfig.PaThreshold) ? spectrum.intensityPulse[i] : spectrum.intensityAnalog[i]);
			}
		}
	}

	private void ProcessMainRunDatas(SpectrumInfos spectrum, int mainIndex, double time)
	{
		foreach (IsotopeInfos isotope in Isotopes)
		{
			double left = isotope.mass - 0.45;
			double right = isotope.mass + 0.55;
			double[] mass = spectrum.mass;
			double[] intensity = spectrum.intensity;
			double cps = intensity.Where((double data, int index) => mass[index] >= left && mass[index] <= right).Average();
			IEnumerable<HPLCTimeSpectrum> tspectrums = timeSpectrums.Where((HPLCTimeSpectrum tspectrum) => tspectrum.SampleId == spectrum.sampleId && tspectrum.RunIndex == mainIndex && tspectrum.Symbol == isotope.symbol);
			if (tspectrums.Any())
			{
				HPLCTimeSpectrum tspectrum2 = tspectrums.First();
				lock (tspectrum2)
				{
					tspectrum2.Time.Add(time);
					tspectrum2.Intensity.Add(cps);
				}
			}
		}
	}

	private void CalculateIntegerationCPS(SamplesInfos sample)
	{
		if (sample.status != 1)
		{
			return;
		}
		IEnumerable<HPLCIntegerRegions> regions = integerRegions.Select((HPLCIntegerRegions region) => region);
		if (!regions.Any())
		{
			return;
		}
		foreach (IsotopeInfos isotope in isotopes)
		{
			int i;
			for (i = 0; i < sample.mains; i++)
			{
				IEnumerable<HPLCTimeSpectrum> tspectrums = timeSpectrums.Where((HPLCTimeSpectrum tspectrum) => tspectrum.SampleId == sample.guid && tspectrum.Symbol == isotope.symbol && tspectrum.RunIndex == i);
				IEnumerable<HPLCAnalyseInfos> results = Results.Where((HPLCAnalyseInfos result) => result.sampleId == sample.guid && result.symbol == isotope.symbol && result.number == i);
				if (!tspectrums.Any() || !results.Any())
				{
					continue;
				}
				HPLCTimeSpectrum tspectrum2 = tspectrums.First();
				double[] time;
				double[] intensity;
				lock (tspectrum2)
				{
					time = tspectrum2.Time.ToArray();
					intensity = tspectrum2.Intensity.ToArray();
				}
				if (time == null || time.Count() <= 0)
				{
					return;
				}
				IEnumerable<HPLCIntegerRegions> _region = regions.Where((HPLCIntegerRegions _regions) => _regions.symbol == isotope.symbol);
				foreach (HPLCIntegerRegions region2 in _region)
				{
					IEnumerable<HPLCAnalyseInfos> rst = results.Where((HPLCAnalyseInfos _result) => _result.regionLabel == region2.ReferenceId && _result.sampleId == region2.sampleId);
					if (!rst.Any())
					{
						continue;
					}
					HPLCAnalyseInfos result2 = rst.First();
					double sum = 0.0;
					int start = 0;
					int end = time.Length - 1;
					for (int idx2 = 0; idx2 < time.Length; idx2++)
					{
						if (time[idx2] >= region2.Start)
						{
							start = idx2;
							break;
						}
					}
					for (int idx = time.Length - 1; idx >= 0; idx--)
					{
						if (time[idx] <= region2.End)
						{
							end = idx;
							break;
						}
					}
					sum = (result2.intensity = CalculateIntegerValue(time, intensity, start, end));
					result2.icps = sum;
					result2.test = true;
				}
			}
		}
	}

	private void CalculateUncorrectCPS(IsotopeInfos isotope)
	{
		foreach (HPLCStatisticResults stat in Statistics.Where((HPLCStatisticResults statistic) => statistic.symbol == isotope.symbol))
		{
			foreach (HPLCIntegerRegions region in integerRegions.Where((HPLCIntegerRegions regions) => regions.symbol == isotope.symbol))
			{
				IEnumerable<double> cpss = from result in Results
					where result.symbol == isotope.symbol && result.regionLabel == region.ReferenceId && result.sampleId == stat.sampleId && result.test && !result.exclude
					select result.intensity;
				if (cpss != null && cpss.Count() > 0)
				{
					stat.avgUICPS = CalculateAverage(cpss.ToArray());
					stat.sdUICPS = CalculateDeviation(cpss.ToArray());
					stat.rsdUICPS = stat.sdUICPS / stat.avgUICPS * 100.0;
				}
			}
		}
	}

	private void CalculateBlankCPS(SamplesInfos sample)
	{
		IEnumerable<SamplesInfos> blkSamples = samples.Where((SamplesInfos s) => s.guid == sample.blank);
		if (!blkSamples.Any())
		{
			return;
		}
		SamplesInfos blkSample = blkSamples.First();
		if (blkSample.status != 1 || sample.status != 1)
		{
			return;
		}
		foreach (IsotopeInfos isotope in isotopes)
		{
			foreach (HPLCIntegerRegions region in integerRegions.Where((HPLCIntegerRegions regions) => regions.symbol == isotope.symbol))
			{
				HPLCStatisticResults blkStat = statistics.Where((HPLCStatisticResults stat) => stat.sampleId == sample.guid && stat.regionLabel == region.ReferenceId && stat.symbol == isotope.symbol).First();
				if (blkStat.avgUICPS < 0.0 || double.IsNaN(blkStat.avgUICPS))
				{
					continue;
				}
				IEnumerable<HPLCAnalyseInfos> destResults = results.Where((HPLCAnalyseInfos result) => result.sampleId == sample.guid && result.regionLabel == region.ReferenceId && result.symbol == isotope.symbol);
				foreach (HPLCAnalyseInfos result2 in destResults)
				{
					result2.icps = result2.intensity - blkStat.avgUICPS;
				}
			}
		}
	}

	private void CalculateCorrectCPS(SamplesInfos sample, IsotopeInfos istd)
	{
		if (sample.status != 1)
		{
			return;
		}
		int i;
		for (i = 0; i < sample.mains; i++)
		{
			HPLCAnalyseInfos istdResult = results.Where((HPLCAnalyseInfos result) => result.sampleId == sample.guid && result.symbol == istd.symbol && result.number == i).First();
			IEnumerable<HPLCAnalyseInfos> destResults = results.Where((HPLCAnalyseInfos result) => result.sampleId == sample.guid && result.number == i && result.symbol != istd.symbol);
			foreach (HPLCAnalyseInfos item in destResults)
			{
				item.icps /= istdResult.icps;
			}
		}
	}

	private void CalculateInterferenceCPS(IsotopeInfos isotope)
	{
		if (isotope.equations == null)
		{
			return;
		}
		foreach (SamplesInfos sample in Samples)
		{
			if (sample.status != 1)
			{
				continue;
			}
			IEnumerable<HPLCAnalyseInfos> cpsResult = Results.Where((HPLCAnalyseInfos result) => result.symbol == isotope.symbol && result.sampleId == sample.guid);
			foreach (HPLCAnalyseInfos result2 in cpsResult)
			{
				result2.icps = InterferenceValue(result2.symbol, result2.sampleId, result2.number);
			}
		}
	}

	private double InterferenceValue(string symbol, int sampleId, int number)
	{
		IsotopeInfos currentIsotope = Isotopes.Find((IsotopeInfos isotope) => isotope.symbol == symbol);
		double icps = 0.0;
		IEnumerable<HPLCAnalyseInfos> results = Results.Where((HPLCAnalyseInfos result) => result.symbol == symbol && result.sampleId == sampleId && result.number == number);
		if (results != null && results.Count() > 0)
		{
			HPLCAnalyseInfos result2 = results.First();
			if (currentIsotope.equations != null && !result2.interferenceCorrected)
			{
				foreach (InterferenceEquation equation in currentIsotope.equations)
				{
					result2.icps += equation.interferenceFactor * InterferenceValue(equation.interferenceSymbol, sampleId, number);
				}
				result2.interferenceCorrected = true;
			}
			icps = result2.icps;
		}
		return icps;
	}

	private void CalculateStatCPS(IsotopeInfos isotope)
	{
		if (isotope.isInterference)
		{
			return;
		}
		foreach (HPLCIntegerRegions region in integerRegions.Where((HPLCIntegerRegions regions) => regions.symbol == isotope.symbol))
		{
			foreach (SamplesInfos sample in Samples)
			{
				if (sample.status == 0)
				{
					continue;
				}
				IEnumerable<double> cpss = from result in Results
					where result.symbol == isotope.symbol && result.regionLabel == region.ReferenceId && result.sampleId == sample.guid && result.test && !result.exclude
					select result.icps;
				if (cpss != null && cpss.Count() > 0)
				{
					double average = CalculateAverage(cpss.ToArray());
					double sd = CalculateDeviation(cpss.ToArray());
					double rsd = sd / average * 100.0;
					HPLCStatisticResults statResult = Statistics.Where((HPLCStatisticResults stat) => stat.symbol == isotope.symbol && stat.regionLabel == region.ReferenceId && stat.sampleId == sample.guid).First();
					statResult.avgCPS = average;
					statResult.sdCPS = sd;
					statResult.rsdCPS = rsd;
				}
			}
		}
	}

	public void CalculateCurve(HPLCIntegerRegions region, bool istd = false)
	{
		IsotopeInfos currentisotope = null;
		IEnumerable<IsotopeInfos> ists = Isotopes.Where((IsotopeInfos Ist) => Ist.symbol == region.symbol);
		if (ists != null && ists.Count() > 0)
		{
			currentisotope = ists.ElementAt(0);
		}
		if (currentisotope == null || currentisotope.inter || currentisotope.method == 0 || currentisotope.method == 3)
		{
			return;
		}
		string currentSymbol = currentisotope.symbol;
		int currentMethod = currentisotope.method;
		string currentlabel = region.ReferenceId;
		List<HPLCStatisticResults> stats = new List<HPLCStatisticResults>();
		stats.AddRange(from result in Statistics
			from sample in Samples
			where result.symbol == currentSymbol && result.regionLabel == currentlabel && result.sampleId == sample.guid && (sample.type == 0 || sample.type == currentMethod) && sample.status == 1
			select result);
		if (stats == null || stats.Count < 2)
		{
			return;
		}
		foreach (HPLCStatisticResults stat in stats)
		{
			IEnumerable<STDConcentration> std = StdConcentration.Where((STDConcentration stdCon) => stdCon.sample == stat.sampleId && stdCon.symbol == stat.symbol && stdCon.Regionlabel == currentlabel);
			if (std != null && std.Count() > 0)
			{
				stat.stdCon = std.ElementAt(0).concentration;
			}
			else
			{
				stat.stdCon = 0.0;
			}
		}
		IEnumerable<double> cps1 = from result in stats
			where result.include && result.stdCon >= 0.0
			select result.avgCPS;
		IEnumerable<double> con1 = from result in stats
			where result.include && result.stdCon >= 0.0
			select result.stdCon;
		if (istd)
		{
			con1 = from result in stats
				where result.include && result.stdCon >= 0.0
				select result.stdCon / (100.0 - result.stdCon);
		}
		if (cps1.Count() <= 0 && con1.Count() <= 0)
		{
			return;
		}
		int points = stats.Where((HPLCStatisticResults result) => result.stdCon >= 0.0).Count();
		double[] kb = null;
		IEnumerable<HPLCStatisticResults> blkResult = from result in stats
			from sample in Samples
			where sample.type == 0 && result.symbol == currentSymbol && result.sampleId == sample.guid && result.include
			select result;
		kb = ((currentisotope.force == 2) ? LSFit.LineFit(con1.ToArray(), cps1.ToArray(), 0.0, 0.0, true) : ((currentisotope.force != 1 || blkResult == null || blkResult.Count() == 0) ? LSFit.LineFit(con1.ToArray(), cps1.ToArray(), 0.0, 0.0, false) : LSFit.LineFit(con1.ToArray(), cps1.ToArray(), blkResult.First().stdCon, blkResult.First().avgCPS, true)));
		if (kb != null)
		{
			IEnumerable<HPLCIsotopeCurve> curves = Curves.Where((HPLCIsotopeCurve curve) => curve.symbol == currentSymbol && curve.regionLabel == currentlabel);
			if (curves != null && curves.Count() == 1)
			{
				curves.ElementAt(0).method = currentMethod;
				curves.ElementAt(0).k = kb[0];
				curves.ElementAt(0).b = kb[1];
				curves.ElementAt(0).r = kb[2];
				curves.ElementAt(0).intercept1 = Math.Abs(kb[1]);
				curves.ElementAt(0).intercept2 = Math.Abs(kb[1] / kb[0]);
				curves.ElementAt(0).calculated = true;
				curves.ElementAt(0).points = points;
				Dirty.CurveDirty = true;
			}
		}
	}

	private void CalculateCon(SamplesInfos sample, bool istd = false)
	{
		if (sample.status != 1)
		{
			return;
		}
		foreach (HPLCIsotopeCurve curve in Curves)
		{
			if (!curve.calculated)
			{
				continue;
			}
			IEnumerable<HPLCAnalyseInfos> conResult = Results.Where((HPLCAnalyseInfos result) => result.sampleId == sample.guid && result.symbol == curve.symbol && result.regionLabel == curve.regionLabel);
			List<double> cons = new List<double>();
			foreach (HPLCAnalyseInfos con in conResult)
			{
				double blkCPS = 0.0;
				bool blkExist = false;
				IEnumerable<HPLCStatisticResults> blkStat = Statistics.Where((HPLCStatisticResults statistic) => statistic.sampleId == sample.blank && statistic.symbol == curve.symbol && statistic.regionLabel == curve.regionLabel);
				if (blkStat != null && blkStat.Count() > 0)
				{
					blkCPS = blkStat.ElementAt(0).avgCPS;
					blkExist = true;
				}
				double c = (con.icps - curve.b) / curve.k;
				if (istd)
				{
					con.concentration = 100.0 * c / (1.0 + c);
				}
				else
				{
					con.concentration = c;
				}
				con.concentration = ((con.concentration < 0.0) ? 0.0 : con.concentration);
				if (!con.exclude)
				{
					cons.Add(con.concentration);
				}
			}
			if (cons != null && cons.Count() > 0)
			{
				double average = CalculateAverage(cons.ToArray());
				double sd = 0.0;
				double rsd = 0.0;
				if (average == double.PositiveInfinity)
				{
					rsd = (sd = double.PositiveInfinity);
				}
				else
				{
					sd = CalculateDeviation(cons.ToArray());
					rsd = sd / average * 100.0;
					average = ((average < 0.0) ? 0.0 : average);
					sd = ((sd < 0.0) ? 0.0 : sd);
					rsd = ((rsd < 0.0) ? 0.0 : rsd);
				}
				HPLCStatisticResults stat = Statistics.Where((HPLCStatisticResults statistic) => statistic.symbol == curve.symbol && statistic.regionLabel == curve.regionLabel && statistic.sampleId == sample.guid).First();
				stat.avgCon = average;
				stat.sdCon = sd;
				stat.rsdCon = rsd;
			}
		}
	}

	private void CalculateRatio(SamplesInfos sample)
	{
		if (sample.status != 1)
		{
			return;
		}
		IEnumerable<RatioResults> results = ratioResults.Where((RatioResults result) => result.SampleId == sample.guid);
		foreach (RatioResults result2 in results)
		{
			IEnumerable<double> numerator = from cps in Results
				where cps.sampleId == sample.guid && cps.symbol == result2.Numerator && cps.number == result2.Number
				select cps.icps;
			IEnumerable<double> denominator = from cps in Results
				where cps.sampleId == sample.guid && cps.symbol == result2.Denominator && cps.number == result2.Number
				select cps.icps;
			result2.Result = numerator.First() / denominator.First();
		}
		IEnumerable<RatioStatistics> statistics = RatioStat.Where((RatioStatistics stat) => stat.SampleId == sample.guid);
		foreach (RatioStatistics stat2 in statistics)
		{
			IEnumerable<double> rs = from result in ratioResults
				where result.Name == stat2.Name && result.SampleId == sample.guid
				select result.Result;
			if (rs != null && rs.Count() > 0)
			{
				stat2.Avg = CalculateAverage(rs.ToArray());
				stat2.Sd = CalculateDeviation(rs.ToArray());
				stat2.Rsd = stat2.Sd / stat2.Avg * 100.0;
			}
		}
	}

	public void RecalculatedAll()
	{
		if (isInCalculate)
		{
			return;
		}
		isInCalculate = true;
		foreach (SamplesInfos sample4 in samples)
		{
			CalculateIntegerationCPS(sample4);
		}
		foreach (IsotopeInfos isotope3 in isotopes)
		{
			CalculateUncorrectCPS(isotope3);
		}
		foreach (SamplesInfos sample3 in samples)
		{
			CalculateBlankCPS(sample3);
		}
		IEnumerable<IsotopeInfos> istds = isotopes.Where((IsotopeInfos istd) => istd.inter);
		if (istds.Any())
		{
			foreach (SamplesInfos sample2 in samples)
			{
				CalculateCorrectCPS(sample2, istds.First());
			}
		}
		foreach (IsotopeInfos isotope in isotopes)
		{
			CalculateStatCPS(isotope);
		}
		foreach (IsotopeInfos isotope2 in Isotopes)
		{
			IEnumerable<HPLCIntegerRegions> regions = integerRegions.Where((HPLCIntegerRegions Regions) => isotope2.symbol == Regions.symbol);
			foreach (HPLCIntegerRegions region in regions)
			{
				CalculateCurve(region);
			}
		}
		foreach (SamplesInfos sample in Samples)
		{
			CalculateCon(sample);
		}
		isInCalculate = false;
		Dirty.ResultsDirty = true;
	}

	private void CalculateISTD(IsotopeInfos isotope)
	{
		if (!isotope.inter)
		{
			return;
		}
		int sampleId = -1;
		IEnumerable<SamplesInfos> refers = Samples.Where((SamplesInfos sample) => sample.refer);
		if (refers.Count() > 0)
		{
			sampleId = refers.First().guid;
		}
		else
		{
			sampleId = Samples.ElementAt(0).guid;
		}
		IEnumerable<double> cpss = from result in Results
			where result.symbol == isotope.symbol && result.sampleId == sampleId && result.test && !result.exclude
			select result.intensity;
		if (cpss == null || cpss.Count() <= 0)
		{
			return;
		}
		double avg = cpss.Average();
		IEnumerable<HPLCAnalyseInfos> results = Results.Where((HPLCAnalyseInfos result) => result.symbol == isotope.symbol);
		foreach (HPLCAnalyseInfos result2 in results)
		{
			result2.icps = result2.intensity / avg;
			result2.concentration = result2.icps;
		}
		foreach (HPLCStatisticResults stat in Statistics.Where((HPLCStatisticResults statistic) => statistic.symbol == isotope.symbol))
		{
			IEnumerable<double> resultsAvg = from result in Results
				where result.symbol == isotope.symbol && result.sampleId == stat.sampleId && result.test && !result.exclude
				select result.intensity / avg;
			if (resultsAvg != null && resultsAvg.Count() > 0)
			{
				HPLCStatisticResults hPLCStatisticResults = stat;
				double avgCon = (stat.avgCPS = CalculateAverage(resultsAvg.ToArray()));
				hPLCStatisticResults.avgCon = avgCon;
				HPLCStatisticResults hPLCStatisticResults2 = stat;
				avgCon = (stat.sdCPS = CalculateDeviation(resultsAvg.ToArray()));
				hPLCStatisticResults2.sdCon = avgCon;
				HPLCStatisticResults hPLCStatisticResults3 = stat;
				avgCon = (stat.rsdCPS = stat.sdCPS / stat.avgCPS * 100.0);
				hPLCStatisticResults3.rsdCon = avgCon;
			}
		}
	}

	private void SetUnCalculateInterference()
	{
		IEnumerable<HPLCAnalyseInfos> results = from result in Results
			from isotope in Isotopes
			where result.symbol == isotope.symbol && isotope.withInterference
			select result;
		foreach (HPLCAnalyseInfos result2 in results)
		{
			result2.interferenceCorrected = false;
		}
	}

	private double CalculateAverage(double[] values)
	{
		if (values != null && values.Length != 0)
		{
			return values.Average();
		}
		return double.NaN;
	}

	private double CalculateDeviation(double[] values)
	{
		if (values == null)
		{
			return double.NaN;
		}
		double sum = 0.0;
		double sum2 = 0.0;
		int counter = 0;
		foreach (double val in values)
		{
			if (!double.IsNaN(val))
			{
				sum += val;
				sum2 += val * val;
				counter++;
			}
		}
		if (counter < 2)
		{
			return double.NaN;
		}
		return Math.Sqrt(((double)counter * sum2 - sum * sum) / (double)counter / (double)(counter - 1));
	}

	public void ChangeSampleLabel(SamplesInfos sample)
	{
		string label = sample.label;
		IEnumerable<HPLCStatisticResults> stats = Statistics.Where((HPLCStatisticResults statistic) => statistic.sampleId == sample.guid);
		foreach (HPLCStatisticResults stat in stats)
		{
			stat.label = label;
		}
		IEnumerable<HPLCAnalyseInfos> results = Results.Where((HPLCAnalyseInfos result) => result.sampleId == sample.guid);
		foreach (HPLCAnalyseInfos result2 in results)
		{
			result2.label = label;
		}
		IEnumerable<STDConcentration> stds = StdConcentration.Where((STDConcentration stdCon) => stdCon.sample == sample.guid);
		foreach (STDConcentration std in stds)
		{
			std.label = label;
		}
		IEnumerable<AcqTime> acqs = acqTimes.Where((AcqTime acq) => acq.SampleId == sample.guid);
		foreach (AcqTime acq2 in acqs)
		{
			acq2.SampleName = label;
		}
		IEnumerable<HPLCTimeSpectrum> tspectrums = timeSpectrums.Where((HPLCTimeSpectrum spectrum) => spectrum.SampleId == sample.guid);
		foreach (HPLCTimeSpectrum spectrum2 in tspectrums)
		{
			spectrum2.SampleLabel = label;
		}
		Dirty.SamplesDirty = true;
	}

	public void CheckReferSample(int rowIndex = -1)
	{
		if (Samples.Count == 0)
		{
			return;
		}
		if (rowIndex == -1)
		{
			IEnumerable<SamplesInfos> refers = Samples.Where((SamplesInfos sample) => sample.refer);
			if (refers.Count() == 0)
			{
				Samples[0].refer = true;
			}
			return;
		}
		foreach (SamplesInfos sample2 in Samples)
		{
			sample2.refer = false;
		}
		Samples[rowIndex].refer = true;
	}

	public void CheckISTDCurve()
	{
		foreach (HPLCIsotopeCurve curve in Curves)
		{
			foreach (IsotopeInfos isotope in Isotopes)
			{
				if (curve.symbol == isotope.symbol)
				{
					if (isotope.inter)
					{
						curve.calculated = false;
					}
					break;
				}
			}
		}
	}

	public void ApplyRegioninAllSamples(SamplesInfos sample, IsotopeInfos isotope)
	{
		IEnumerable<HPLCIntegerRegions> regions = IntegerRegions.Where((HPLCIntegerRegions Regions) => Regions.sampleId == sample.guid && Regions.symbol == isotope.symbol);
		if (regions == null || regions.Count() <= 0)
		{
			return;
		}
		foreach (HPLCIntegerRegions region in regions)
		{
			foreach (SamplesInfos sa in samples)
			{
				if (sa.guid == sample.guid)
				{
					continue;
				}
				IEnumerable<HPLCIntegerRegions> regs = IntegerRegions.Where((HPLCIntegerRegions Regs) => Regs.sampleId == sa.guid && Regs.symbol == isotope.symbol && Regs.ReferenceId == region.ReferenceId);
				HPLCIntegerRegions reg = regs.First();
				reg.Startindex = region.Startindex;
				reg.EndIndex = region.EndIndex;
				reg.Label = region.Label;
				IEnumerable<HPLCTimeSpectrum> spectrum = timeSpectrums.Where((HPLCTimeSpectrum specs) => specs.SampleId == sa.guid && specs.Symbol == isotope.symbol);
				if (spectrum != null && spectrum.Count() > 0 && reg.Startindex > 0 && reg.EndIndex > 0)
				{
					reg.Start = spectrum.First().Time[reg.Startindex];
					reg.End = spectrum.First().Time[reg.EndIndex];
					if (reg.Startindex >= 0 && reg.EndIndex >= 0)
					{
						reg.Area = CalculateIntegerValue(spectrum.First().Time.ToArray(), spectrum.First().Intensity.ToArray(), reg.Startindex, reg.EndIndex);
						reg.PositionIndex = FindPeak(spectrum.First().Intensity.ToArray(), reg.Startindex, reg.EndIndex);
						reg.Peak = spectrum.First().Intensity[reg.PositionIndex];
						reg.PeakPostion = spectrum.First().Time[reg.PositionIndex];
					}
				}
			}
		}
	}

	private int FindPeak(double[] v, int start, int end)
	{
		int index = -1;
		double max = v[start];
		for (int i = start + 1; i < end; i++)
		{
			if (v[i] > max)
			{
				max = v[i];
				index = i;
			}
		}
		return index;
	}

	public void SetResultExclude(string regionlabel, int sampleId, int num, bool exclude)
	{
		IEnumerable<HPLCAnalyseInfos> results = Results.Where((HPLCAnalyseInfos result) => result.regionLabel == regionlabel && result.sampleId == sampleId && result.number == num);
		if (results != null && results.Count() > 0)
		{
			results.ElementAt(0).exclude = exclude;
		}
	}

	public void SetUnTested()
	{
		foreach (HPLCAnalyseInfos result in Results)
		{
			result.SetUnTested();
		}
		foreach (HPLCStatisticResults stat in Statistics)
		{
			stat.SetUnTested();
		}
		foreach (SamplesInfos sample in Samples)
		{
			sample.SetUnTested();
		}
		foreach (HPLCIsotopeCurve curve in Curves)
		{
			curve.SetUnTested();
		}
		foreach (RatioResults ratio in RatioResults)
		{
			ratio.SetUnTested();
		}
		Scan.SetUnTested();
	}

	public void SetupSampleAcqTimes()
	{
		acqTimes.RemoveAll((AcqTime acq) => !samples.Exists((SamplesInfos sample) => sample.guid == acq.SampleId));
		List<AcqTime> acqs = new List<AcqTime>();
		foreach (SamplesInfos sample2 in samples)
		{
			AcqTime acq2 = new AcqTime
			{
				SampleId = sample2.guid,
				SampleName = sample2.label
			};
			AcqTime tacq = acqTimes.Find((AcqTime a) => a.SampleId == sample2.guid);
			if (tacq != null)
			{
				acq2.Time = tacq.Time;
				acq2.Sweeps = tacq.Sweeps;
			}
			acqs.Add(acq2);
		}
		acqTimes.Clear();
		acqTimes.AddRange(acqs);
	}

	private double CalculateIntegerValue(double[] time, double[] intensity, int start, int end)
	{
		if (time == null || end == start)
		{
			return 0.0;
		}
		double sum = 0.0;
		for (int i = start; i <= end - 1; i++)
		{
			sum += (intensity[i + 1] + intensity[i]) * (time[i + 1] - time[i]) / 2.0;
		}
		return sum - 0.5 * (intensity[end] + intensity[start]) * (time[end] - time[start]);
	}

	public void OnIsotopeChanged()
	{
		SortIsotopes();
		if (this.isotopeChanged != null)
		{
			this.isotopeChanged(null, null);
		}
	}

	public void OnIstdChanged()
	{
		CheckISTDCurve();
		if (this.istdChanged != null)
		{
			this.istdChanged(null, null);
		}
	}

	public void OnSampleChanged()
	{
		Dirty.SamplesDirty = true;
		if (this.sampleChanged != null)
		{
			this.sampleChanged(null, null);
		}
	}

	public void OnSamplerChanged()
	{
		if (this.IsAutoSamplerChangedEvent != null)
		{
			this.IsAutoSamplerChangedEvent(null, null);
		}
	}

	public void OnMethodChanged()
	{
		CheckISTDCurve();
		if (this.methodChanged != null)
		{
			this.methodChanged(null, null);
		}
	}

	public void OnRegionChanged()
	{
		Dirty.RegionDirty = true;
		if (this.regionChanged != null)
		{
			this.regionChanged(null, null);
		}
	}
}
